import React, { useCallback, useState } from 'react';
import { Common } from 'UtilsCommon';
import { Link } from 'Configs';
import Base from './base';

export default (props) => {
  const { property, view, pageAxis } = Base.getProps(props);
  const [isVisible, setIsVisible] = useState(property.isVisible !== false);
  const [value, setValue] = useState(property.value || property.defaultValue || property.text);

  property.setIsVisible = (v) => setIsVisible(v);
  property.setValue = (v) => setValue(v);
  property.setLoading = (v) => { property.loading = v; };

  const clickAction = useCallback(() => {
    if (property.loading) return;
    if (property.eventActionName) pageAxis.invokeEventAction(property.eventActionName, { property, view, pageAxis });
    else if (property.eventAction) pageAxis.invokeEventAction2(property.eventAction, { property, view, pageAxis });
  }, [property, view, pageAxis]);

  if (!isVisible) return null;

  const { width, height, alignItems, isDiv, className, eventActionName, eventAction, cssAnimation, justifyContent, isButton, linkUrl } = property;

  const style = property.style ? { ...property.style } : {};

  if (!style.display && (alignItems || justifyContent)) style.display = "flex";
  if (width) style.width = width;
  if (height) style.height = height;
  if (alignItems) style.alignItems = alignItems;
  if (justifyContent) style.justifyContent = justifyContent;

  let onClick;
  if (eventActionName || eventAction) onClick = clickAction;

  const spanStyle = Common.getStyle(property.spanStyle ? { ...property.spanStyle } : {});

  if (cssAnimation && cssAnimation.invokeContent) {
    const as = JSON.parse(cssAnimation.invokeContent);
    for (const key in as) spanStyle[key] = as[key];
  }
  const spanClassName = [];
  if (isButton) spanClassName.push("buttonActive");

  if (linkUrl) {
    if (linkUrl.toLowerCase().indexOf('http') >= 0) {
      if (isDiv) {
        return <div className={className} style={style}>
          <a className={spanClassName.join(' ')} href={linkUrl} style={spanStyle}>{value}</a>
        </div>;
      }
      return <a className={spanClassName.join(' ')} href={linkUrl} style={spanStyle}>{value}</a>;
    }
    else {
      if (isDiv) {
        return <div className={className} style={style}>
          <Link className={spanClassName.join(' ')} to={linkUrl} style={spanStyle}>{value}</Link>
        </div>;
      }
      return <Link className={spanClassName.join(' ')} to={linkUrl} style={spanStyle}>{value}</Link>;
    }
  }

  if (isDiv) {
    return <div className={className} style={style}>
      <span className={spanClassName.join(' ')} onClick={onClick} style={spanStyle} >{value}</span>
    </div>;
  }

  return <span className={spanClassName.join(' ')} onClick={onClick} style={spanStyle} >{value}</span>;
};